<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import orderDetailStatus from './components/order-detail-status.vue'
import OrderGoodSpec from '@/components/order/order-good-spec.vue'
import ShopNav from '@/components/order/shop-nav.vue'
import { usePaymentCn } from '@/hooks/usePaymentCn'
import { getOrderDetailsConfig, getOrderDetailStatusPlus } from '@/hooks/useOrderStatus'
import { doGetOrderInfo } from '@/apis/order'
import RemarkView from './components/remark-view.vue'
import type { ApiOrder, OrderDiscount } from '@/pages/order/types'
import type { ApiLogistics01 } from './types'
import Decimal from 'decimal.js'

const { divTenThousand } = useConvert()
const info = ref<ApiOrder>()
// 订单备注信息
const remark = ref<{ [x: string]: string }>({})
// const isLoad = ref(false)
// 第一个包裹的订单快递信息（快递公司，快递单号等）
const logistics = ref<ApiLogistics01>()
//  物流轨迹
const currentDeliveryLocation = ref({
    areaCode: '',
    areaName: '',
    context: '',
    ftime: '',
    status: '',
    time: '',
})
const show = ref(false)
const pathOrderInfo = ref({
    orderNo: '',
    shopId: '',
    packageId: '',
})
const orderDetailsConfig = ref({
    isShowAfsBtn: false,
    isShowFooterBtn: false,
    isShowFooterRightBtnText: '',
    isShowModifyAddressBtn: false,
})

onLoad(({ orderNo, shopId, packageId }) => {
    console.log('orderNo', orderNo)
    if (!orderNo) return uni.navigateBack({ delta: 1 })
    pathOrderInfo.value = {
        orderNo,
        shopId: shopId || '',
        packageId: packageId || '',
    }
    initOrderData(orderNo, shopId, packageId)
})

const couponTypeData = {
    PLATFORM_COUPON: {
        name: '平台优惠券',
        price: new Decimal(0),
    },
    SHOP_COUPON: {
        name: '店铺优惠券',
        price: new Decimal(0),
    },
    freightPrice: {
        name: '运费',
        price: new Decimal(0),
    },
    MEMBER_DEDUCTION: {
        name: '会员优惠',
        price: new Decimal(0),
    },
    FULL_REDUCTION: {
        name: '满减',
        price: new Decimal(0),
    },
    CONSUMPTION_REBATE: { name: '消费返利优惠', price: new Decimal(0) },
}
/**
 * 订单的数据
 */
async function initOrderData(orderNo: string, shopId?: string, packageId?: string) {
    const { code, data } = await doGetOrderInfo(orderNo, shopId, packageId)
    if (code !== 200) return uni.showToast({ title: '获取订单详情失败', icon: 'none' })
    if (!data) {
        uni.navigateBack({
            delta: 1,
        })
        return
    }
    const order = data as ApiOrder
    order.orderDiscounts.forEach((item: OrderDiscount) => {
        couponTypeData[item.sourceType].price =
            couponTypeData[item.sourceType].price.add(
                item.discountItems.map((item) => new Decimal(item.discountAmount)).reduce((pre, current) => current.add(pre)),
            ) || 0
    })
    couponTypeData.freightPrice.price = order.shopOrders
        .flatMap((shopOrder) => shopOrder.shopOrderItems)
        .map((shopOrderItem) => new Decimal(shopOrderItem.freightPrice))
        .reduce((pre, current) => current.add(pre))
    info.value = order
    initRemark(order.shopOrders[0].remark)
    orderDetailsConfig.value = getOrderDetailsConfig(order)
}
// 备注转义
function initRemark(params: any) {
    remark.value = JSON.parse(params)
}
/**
 * 订单状态
 */
const orderStatus = computed(() => getOrderDetailStatusPlus(info.value))
/**
 * 总价格计算（未减去优惠价）
 * fixPrice 除不尽的时候展示的价格
 */
function payAmountComputed(info: ApiOrder) {
    const shopOrder = info.shopOrders.flatMap((shopOrder) => shopOrder.shopOrderItems)
    const payAmount = shopOrder.reduce((p, item) => {
        return p.add(new Decimal(item.dealPrice).mul(new Decimal(item.num)).sub(item.fixPrice))
    }, new Decimal(0))
    return divTenThousand(payAmount).toNumber() < 0 ? 0 : divTenThousand(payAmount)
}
/**
 * 优惠后的实付金额
 */
const amountRealPay = computed(() => {
    if (info.value) {
        const amount = payAmountComputed(info.value)
        const totalPrice = new Decimal(amount)
        const totalPrice_ = totalPrice.toNumber() < 0 ? new Decimal(0) : totalPrice // 运费不参与优惠计算 最后相加
        return totalPrice_.add(divTenThousand(couponTypeData.freightPrice.price))
    }
    return 0
})
</script>

<template>
    <view class="order-detail">
        <order-detail-status
            :status="orderStatus.desc"
            :count-down-show="info?.status === 'UNPAID'"
            :order="info"
            :rule-str="info?.status"
            :update-time="info?.createTime"
            :pay-time-out="info?.timeout?.payTimeout || '0'"
        />
        <view v-for="item in info?.shopOrders || []" :key="item.no" class="good">
            <shop-nav :is-detail="true" :info="item" class="good__nav" />
            <view class="good__pack">
                <order-good-spec
                    v-for="ite in item.shopOrderItems"
                    :key="ite.id"
                    :is-show-btn="orderDetailsConfig.isShowAfsBtn"
                    :pay-status="info?.status"
                    :is-detail="true"
                    :info="ite"
                    :order-no="info?.no"
                />
            </view>
        </view>
        <view class="info">
            <view v-for="item in couponTypeData" v-show="Number(item.price)" :key="item.name" class="info__item">
                <view>{{ item.name }}</view>
                <view class="info__item--number">{{ divTenThousand(item.price) }}</view>
            </view>
            <view v-if="info?.orderPayment" class="info__item">
                <view>支付总金额</view>
                <view class="info__item--number">{{ amountRealPay }}</view>
            </view>
        </view>
        <view v-if="info?.orderPayment" class="detail">
            <view class="detail__item">订单编号：{{ info?.no }}</view>
            <view class="detail__item">支付方式：{{ usePaymentCn(info?.orderPayment?.type) }}</view>
            <view class="detail__item">创建时间：{{ info?.createTime }}</view>
            <view class="detail__item">预约提货时间：{{ info?.extra?.packUpTime }}</view>
            <view v-show="orderStatus.isClosed" class="detail__item">关闭时间：{{ orderStatus.closeTime }}</view>
            <remark-view class="detail__item" :remark="remark"></remark-view>
        </view>
    </view>
</template>
<style lang="scss" scoped>
@import '@/assets/css/mixins/mixins.scss';
@include b(load) {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
@include b(order-detail) {
    padding-bottom: 120rpx;
}
@include b(distribution) {
    box-sizing: border-box;
    margin: 0 20rpx;
    height: 90rpx;
    @include flex(space-between);
    border-bottom: 1px solid rgb(216, 214, 214);
}
@include b(tracking) {
    box-sizing: border-box;
    @include flex(space-between);
    padding: 20rpx 0;
    margin: 0 20rpx;
    border-bottom: 1px solid rgb(216, 214, 214);
    @include e(left) {
        @include flex(flex-start, flex-start);
        @include m(info) {
            font-size: 26rpx;
            color: #36bb28;
        }
        @include m(date) {
            font-size: 24rpx;
            color: #959595;
        }
    }
    @include e(left-text) {
        margin-left: 10rpx;
        @include flex(space-between, flex-start);
        flex-direction: column;
    }
    @include e(icon) {
        transform: rotate(-90deg);
    }
}
@include b(address) {
    box-sizing: border-box;
    padding: 20rpx 20rpx;
    @include flex(space-between);
    font-size: 30rpx;
    @include e(left) {
        @include flex(flex-start, flex-start);
        @include m(title) {
        }
        @include m(content) {
            width: 360rpx;
            color: #ccc;
            font-size: 26rpx;
            margin-top: 6rpx;
        }
    }
    @include e(right) {
        height: 115rpx;
        @include m(mobile) {
            color: #ccc;
        }
    }
}
@include b(good) {
    margin-top: 10rpx;
    @include e(nav) {
        background: #fff;
        padding: 0 20rpx;
    }
    @include e(packs) {
        margin-bottom: 12rpx;
    }
    @include e(packNum) {
        padding: 0 20rpx;
        height: 80rpx;
        font-weight: bold;
        line-height: 80rpx;
        border-bottom: 1px solid #f5f5f5;
        background: #fff;
    }
    @include e(pack) {
        padding: 20rpx;
        background: #fff;
    }
}
@include b(info) {
    box-sizing: border-box;
    padding: 20rpx;
    background: #fff;
    margin-top: 10rpx;
    font-size: 28rpx;
    color: #333;
    @include e(item) {
        height: 80rpx;
        @include flex(space-between);
        @include m(number) {
            color: #a1a1a1;
            &::before {
                content: '￥';
                display: inline-block;
                font-size: 24rpx;
            }
        }
    }
}
@include b(detail) {
    padding: 40rpx 20rpx;
    background: #fff;
    font-size: 28rpx;
    color: #ccc;
    margin-top: 10rpx;
    @include e(item) {
        margin-bottom: 6rpx;
    }
}
@include b(footer-btn) {
    position: fixed;
    bottom: 0;
    @include flex;
    width: 100vw;
    height: 88rpx;
    z-index: 9999;
    @include e(flex) {
        flex: 1;
        text-align: center;
        line-height: 88rpx;
    }
    @include e(left) {
        background: #fff;
        color: #000;
        z-index: 9999;
    }
    @include e(right) {
        color: #ffffff;
        background: #fe4e63;
    }
}
@include b(right) {
    z-index: 9999;
    color: #ffffff;
    background: #fe4e63;
}
</style>
